
var express = require('express');
var bodyParser = require('body-parser');

var H = require('./lib/utils');
//var E = require('./lib/encryptionutils');

var app = express();

app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded

var Redis = require('ioredis');

var cluster = new Redis.Cluster([{
    port: 7401,
    host: '192.168.1.201'
}, {
    port: 7402,
    host: '192.168.1.201'
}, {
    port: 7403,
    host: '192.168.1.201'
}, {
    port: 7404,
    host: '192.168.1.201'
}, {
    port: 7405,
    host: '192.168.1.201'
}, {
    port: 7406,
    host: '192.168.1.201'
}]);

//cluster.set('foo', 'bar');
//cluster.get('foo', function (err, res) {
//    // res === 'bar'
//    console.log('respond: ' + res)
//});

app.get('/ids/testConn.action', function(req, res) {
    res.send('OK');
});

app.get('/ids/listAdsOfBeaconsMem.action', function(req, res) {

    var triggerType = req.query.triggerType;
    var jsonBeacons = req.query.jsonBeacons;
    var appToken = req.query.appToken;

    var beacons = JSON.parse(jsonBeacons);

    var total = 0;
    H.each(H.wrap(beacons).sortBy(function(idsbeacon) {
        return idsbeacon.rssi;
    }), function(beacon) {
        var key = "UMM:POSID:" + beacon.proximityUuid.toUpperCase() + ":" + beacon.major + ":" + beacon.minor;
        cluster.get(key, function(err, response) {
            beacon.posId = response;
            total++;
            if (total === beacons.length) {
                //got
                var valids = H.wrap(beacons).filter(function(beacon) {
                    return beacon && beacon.posId !== null && beacon.posId != 'null';
                }).toArray();
                var filtered = [];
                H.each(valids, function(v) {
                    if (v) filtered.push(v);
                });
                //console.log('got umm: ' + beacons.length + " valid count: " +valids.length + " filtered: " + filtered.length)
                var validCount = 0;
                H.each(filtered, function(b) {
                    if (!b) return;
                    var k = "POSID:PLANID:" + b.posId;
                    cluster.zrange(k, 0, -1, 'WITHSCORES', function(e, r) {
                        validCount++;
                        b.planId = (r || [])[0];
                        if (validCount === filtered.length) {
                            //got
                            //console.log('got adplan ids ' + validCount)
                            var list = H.wrap(filtered).filter(function(beacon) {
                                return beacon && beacon.planId !== undefined && beacon.planId !== null && beacon.planId != 'null';
                            });
                            var flist = [];
                            H.each(list, function(f) {
                                if (f) flist.push(f);
                            });
                            //console.log('filtered: ' + flist.length)
                            var listCount = 0;
                            H.wrap(flist).each(function(beacon) {
                                if (!beacon) return;
                                var key = "ADPLAN:ADC:" + beacon.planId;
                                //console.log(key)
                                cluster.get(key, function(e, r) {
                                    listCount++;
                                    beacon.ad = r;
                                    if (r !== null && r != 'null' && typeof r === 'string') {
                                        try {
                                            beacon.ad = JSON.parse(r);
                                        } catch (e) {}
                                    }
                                    //r is ad json
                                    if (listCount === flist.length) {
                                        //got
                                        //console.log(JSON.stringify(flist, null, ' '));
                                        var valid = [];
                                        H.each(flist, function(f) {
                                            if (f && f.ad && f.ad != 'null') valid.push(f.ad);
                                        });
                                        //console.log('got ad ' + valid.length)
                                        //console.log(JSON.stringify(valid));
                                        res.send(JSON.stringify(valid || {}));
                                    }
                                });
                            });
                        }
                    });
                });
                //res.send('OK')
            }
        });
    });

    //var s = Math.random() * 22;
    //s = ~~s + 1;
    //s = (s < 10 ? "0" : "") + s;
    //res.send(s + ".jpg");
});

var http = require('http');
var https = require('https');

var fs = require('fs');

var httpServer = http.createServer(app);

try {
    var privateKey  = fs.readFileSync('/etc/ssl/private/play_sagnitude_com.key', 'utf8');
    var certificate = fs.readFileSync('/etc/ssl/private/play_sagnitude_com.bundle.crt', 'utf8');

    var credentials = {key: privateKey, cert: certificate};

    var httpsServer = https.createServer(credentials, app);

    httpsServer.listen(9694);

    console.log('network service at https://localhost:9984');
} catch (e) {
    console.log('https not enabled');
}

httpServer.listen(9692);

console.log('network service at http://localhost:9982');